const { pool } = require('../config/db');

exports.getSystemStatus = async (req, res) => {
    try {
        const [[row]] = await pool.query('SELECT visit_count, threshold FROM system_status WHERE id = 1');
        if (!row) {
            return res.status(404).send('System status not found');
        }
        return res.json(row);
    } catch (error) {
        console.error('Error getting system status:', error);
        res.status(500).send('Failed to get system status');
    }
};

exports.updateThreshold = async (req, res) => {
    try {
        const updates = req.body;
        
        // 验证是否有要更新的字段
        if (!updates || Object.keys(updates).length === 0) {
            return res.status(400).send('No fields to update');
        }
        
        // 构建动态更新查询
        const fields = [];
        const values = [];
        
        if (updates.threshold !== undefined) {
            // 验证阈值是否为有效数字
            if (isNaN(updates.threshold) || updates.threshold < 0) {
                return res.status(400).send('Threshold must be a non-negative number');
            }
            fields.push('threshold = ?');
            values.push(updates.threshold);
        }
        
        if (updates.visit_count !== undefined) {
            // 验证访问计数是否为有效数字
            if (isNaN(updates.visit_count) || updates.visit_count < 0) {
                return res.status(400).send('Visit count must be a non-negative number');
            }
            fields.push('visit_count = ?');
            values.push(updates.visit_count);
        }
        
        if (fields.length === 0) {
            return res.status(400).send('No valid fields to update');
        }
        
        // 执行更新
        await pool.query(
            `UPDATE system_status SET ${fields.join(', ')} WHERE id = 1`, 
            values
        );
        
        // 获取更新后的数据
        const [[updatedStatus]] = await pool.query('SELECT visit_count, threshold FROM system_status WHERE id = 1');
        
        return res.json({
            message: 'System status updated successfully',
            status: updatedStatus
        });
    } catch (error) {
        console.error('Error updating system status:', error);
        res.status(500).send('Failed to update system status');
    }
};

exports.incrementVisitCount = async (req, res) => {
    try {
        // 增加访问计数
        await pool.query('UPDATE system_status SET visit_count = visit_count + 1 WHERE id = 1');
        
        // 获取更新后的数据
        const [[updatedStatus]] = await pool.query('SELECT visit_count, threshold FROM system_status WHERE id = 1');
        
        return res.json({
            message: 'Visit count incremented successfully',
            status: updatedStatus
        });
    } catch (error) {
        console.error('Error incrementing visit count:', error);
        res.status(500).send('Failed to increment visit count');
    }
};
